package com.zutclassdemo.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zutclassdemo.entity.TAdmin;
import com.zutclassdemo.entity.TRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MyUserDetailService implements UserDetailsService {// 自定义认证配置

    @Autowired
    private ITAdminService adminService;

    @Autowired
    private ITRoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if(StrUtil.isEmpty(username)){
            throw new RuntimeException("用户名不能为空");
        }
        LambdaQueryWrapper<TAdmin> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(TAdmin::getUsername,username);
        TAdmin admin = adminService.getOne(lambdaQueryWrapper);
        if(admin==null){
            throw new UsernameNotFoundException(String.format("%s用户不存在",username));
        }
        List<GrantedAuthority> authorities = new ArrayList<>();
        List<TRole> roles = roleService.getRoleById(admin.getId());
        roles.forEach(role->{
            authorities.add(new SimpleGrantedAuthority(role.getName()));
            System.out.println(role.getName());
        });
        return new User(admin.getUsername(),admin.getPassword(),authorities);
    }
}
